import axios from 'axios'
import ElementPlus from 'element-plus'
import {getTokenHead, getToken, setToken, getRefreshToekn, setRefreshToekn} from '@/utils/auth'

// create an axios instance
const service = axios.create({
  baseURL: "/api", // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 10000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    config.headers['Authorization'] = getTokenHead() + " " + getToken()
    if (getToken()!==undefined) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation

    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug

    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    if(response.code!==200){
      // ElMessage.error('Oops, this is a error message.')
    }
    const res = response.data
    if(res === "未登录或token过期" && getRefreshToekn()!=="undefined"){
      axios({
        url: '/api/auth/oauth/token',
        method: 'post',
        params:{
          grant_type: 'refresh_token',
          client_id: 'client-app',
          client_secret: '123456',
          refresh_token: getRefreshToekn(),
        }
      }).then(res=>{
        console.log(res)
        setToken(res.data.access_token)
        setRefreshToekn(res.data.refresh_token)
        console.log("重新获得token")
      },err=>{
        console.log(err)
      })
    }
    // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
    if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
      // to re-login
      return Promise.reject(new Error(res.message || 'Error'))
    }

    return res
  },
  error => {
    console.log('err' + error) // for debug
    return Promise.reject(error)
  }
)

export default service
